package com.atguign.gulimall.ware.config;

import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Configuration
@EnableFeignClients(basePackages = "com.atguign.gulimall.ware.feign")
public class FeignConfig {
    /**
     * feign远程调用之前，拦截请求，把请求头中的Cookie值给到远程服务
     * @return
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return template -> {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null) {
                HttpServletRequest request = requestAttributes.getRequest();
                log.debug("Cookie: {}", request.getHeader("Cookie"));
                template.header("Cookie", request.getHeader("Cookie"));
            }
        };
    }
}
